/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.admin.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Directory;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.service.DirectoryService;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of editing a
 * group,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class EditGroupAction extends AbstractAction {

	private static final long serialVersionUID = -1098078436221153089L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;
	public static final int NOT_LOGGED = 2;
	// parameter/attributes constants

	public static final String CMD_VALUE = "editGroup";

	// utility constants
	public static final String ONE = "1";
	public static final String ZERO = "0";
	public static final String VIEWER = "viewer";
	public static final long MAX_SIZE = (3 * 1024 * 1024);

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {

		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		boolean notLogged = (Boolean) request
				.getAttribute(PageConstants.NOTLOGGED);
		if (notLogged)
			return NOT_LOGGED;
		GroupService groupService = new GroupService();
		String gid = request.getParameter(PageConstants.ID);
		Group group = null;
		if (gid != null) {
			group = groupService.findById(new Integer(gid));
		}
		if (group != null && isAdmin) {

			request.setAttribute(PageConstants.GROUP, group);

			return ACCESS_ALLOWED;
		}

		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (NOT_LOGGED == validationResult) {
			request.setAttribute("init", "login");
			return "/";
		}
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;
		return PageConstants.PAGE_PATH_EDITGROUP;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		if (ACCESS_ALLOWED == validationResult) {

			editGroup(request);

			getGroups(request);

		}
		// TODO Auto-generated method stub

	}

	private void editGroup(HttpServletRequest request) {

		String cmd = request.getParameter(PageConstants.CMD);

		if (CMD_VALUE.equals(cmd)) {
			try {

				String webInfPath = this.getServletConfig().getServletContext()
						.getRealPath("WEB-INF");
				String rootPath = webInfPath.substring(0,
						webInfPath.indexOf("WEB-INF"));
				String uploadPath = rootPath + PageConstants.GROUP_AVATAR_PATH;
				String tempPath = rootPath + PageConstants.UPLOAD_TEMP_PATH;
				HttpSession session = request.getSession(true);
				String lang = (String) session.getAttribute(Messages.LANG);
				GroupService groupService = new GroupService();
				Group group = (Group) request.getAttribute(PageConstants.GROUP);
				String info = null;
				String pic = group.getPic();
				String name = null;
				String notice = Symbols.BLANK;
				String open = ONE;
				String up = ZERO;
				String func = ZERO;
				String local = ONE;
				String en = ONE;
				String msg = null;
				String nav = "0";
				if (!new File(uploadPath).isDirectory())
					new File(uploadPath).mkdirs();
				if (!new File(tempPath).isDirectory())
					new File(tempPath).mkdirs();
				DiskFileUpload fileUpload = new DiskFileUpload();

				fileUpload.setSizeMax(MAX_SIZE);

				fileUpload.setSizeThreshold(4096);

				fileUpload.setRepositoryPath(tempPath);

				@SuppressWarnings("rawtypes")
				List fileItems = fileUpload.parseRequest(request);
				@SuppressWarnings("rawtypes")
				Iterator fileItemIterator = fileItems.iterator();

				while (fileItemIterator.hasNext()) {
					FileItem fileItem = (FileItem) fileItemIterator.next();

					if (fileItem.isFormField()) {
						if (fileItem.getFieldName().equals(PageConstants.NAME)) {
							name = fileItem
									.getString(PageConstants.ENCODING_UTF8);
							if (!name.equals(group.getName())
									&& groupService.isUsedName(name) == 1) {

								if (lang != null
										&& lang.equals(Messages.LANG_EN)) {
									msg = Messages
											.getELabel(Messages.MSG_NAME_CONFLICT);
								} else {
									msg = Messages
											.getLabel(Messages.MSG_NAME_CONFLICT);
								}

								request.setAttribute(PageConstants.MSG, msg);
								return;

							}
						} else if (fileItem.getFieldName().equals(
								PageConstants.INFO))
							info = fileItem
									.getString(PageConstants.ENCODING_UTF8);
						else if (fileItem.getFieldName().equals(
								PageConstants.NOTICE))
							notice = fileItem
									.getString(PageConstants.ENCODING_UTF8);
						else if (fileItem.getFieldName().equals(
								PageConstants.OPEN)) {
							open = fileItem.getString();
							if ("11".equals(open)) {
								open = PageConstants.ONE;
								nav = PageConstants.ONE;
							} else if ("22".equals(open)) {
								open = "2";
								nav = PageConstants.ONE;
							}
						} else if (fileItem.getFieldName().equals(
								PageConstants.UP))
							up = fileItem.getString();
						else if (fileItem.getFieldName().equals(
								PageConstants.FUNC))
							func = fileItem.getString();

						else if (fileItem.getFieldName().equals(
								Messages.LANG_LOCAL))
							local = fileItem.getString();
						else if (fileItem.getFieldName().equals(
								Messages.LANG_EN))
							en = fileItem.getString();
						 

					}
					if (!fileItem.isFormField()) {
						int fileError = 0;
						String fileName = fileItem.getName();
						if (fileName != null)
							fileName = fileName
									.substring(fileName
											.lastIndexOf(Symbols.DOUBLE_BACK_SLASH) + 1);
						if (fileName == null || fileName.equals(Symbols.BLANK))
							fileError = 1;
						String suffixName = null;
						if (fileError != 1) {
							suffixName = Symbols.DOT
									+ fileName.substring(fileName
											.lastIndexOf(Symbols.DOT) + 1);

							fileName = new java.sql.Timestamp(
									System.currentTimeMillis()).toString()
									.substring(0, 13)
									+ new java.sql.Timestamp(
											System.currentTimeMillis())
											.toString().substring(14, 16)
									+ new java.sql.Timestamp(
											System.currentTimeMillis())
											.toString().substring(17, 19)
									+ suffixName;

							if (suffixName.equals(".JPG")
									|| suffixName.equals(".jpg")
									|| suffixName.equals(".GIF")
									|| suffixName.equals(".gif")
									|| suffixName.equals(".BMP")
									|| suffixName.equals(".bmp")) {
								pic = "group/upload/images/" + fileName;

								File savedFile = new File(uploadPath, fileName); //

								fileItem.write(savedFile);// fi

								File f = new File(rootPath + "group/"
										+ group.getPic());
								if (f.exists()
										&& group.getPic().indexOf("group.gif") == -1)
									f.delete();

							}

						}

					}

				}
				if (name != null)
					group.setName(name);
				if (info != null)
					group.setInfo(info);
				if (pic != null)
					group.setPic(pic);
				group.setNotice(notice);
				group.setOpen(new Integer(open));
				group.setFunc(new Integer(func));
				group.setLocal(new Integer(local));
				group.setNav(new Integer(nav));
				group.setEn(new Integer(en));
				groupService.merge(group);

				int newUp = new Integer(up).intValue();

				if (newUp > 0) {
					int start = 0, end = 0;
					List<Group> groupList = null;
					DirectoryService directoryService = new DirectoryService();
					List<Directory> directories = directoryService
							.findByGid(group.getId());
					if (directories != null && directories.size() > 0) {
						Directory directory = (Directory) directories.get(0);
						groupList = groupService.findGroupsByDid(directory
								.getId());

					} else {
						int parent = 0;
						if (group.getOpen() == 1 && group.getNav() == 0)
							parent = -1;
						else if (group.getOpen() == 1 && group.getNav() == 1)
							parent = -11;
						else if (group.getOpen() == 2 && group.getNav() == 0)
							parent = -2;
						else if (group.getOpen() == 2 && group.getNav() == 1)
							parent = -22;
						else if (group.getOpen() == 3)
							parent = -3;
						else if (group.getOpen() == 4)
							parent = -4;

						groupList = groupService.findGroupsByNotInDirectories(
								group.getOpen(), group.getNav(), parent);
					}

					if (groupList != null) {

						for (int count = 0; count < groupList.size(); count++) {
							Group groupObject = (Group) groupList.get(count);

							groupObject.setUp(count + 1);

							if (groupObject.getId().intValue() == group.getId()
									.intValue())
								group = (Group) groupService.merge(groupObject);
							else
								groupService.merge(groupObject);
						}
						if (newUp > groupList.size())
							newUp = groupList.size();
						int originalUp = group.getUp();

						if (newUp < originalUp) {
							start = newUp;
							end = originalUp < groupList.size() ? originalUp
									: groupList.size();
							for (int count = start - 1; count < end - 1; count++) {
								Group groupObject = (Group) groupList
										.get(count);

								groupObject.setUp(groupObject.getUp() + 1);

								groupService.merge(groupObject);
							}
							group.setUp(newUp);
							group = (Group) groupService.merge(group);

						} else if (newUp > originalUp) {
							start = originalUp;
							end = newUp < groupList.size() ? newUp : groupList
									.size();
							for (int count = start; count < end; count++) {
								Group groupObject = (Group) groupList
										.get(count);

								groupObject.setUp(groupObject.getUp() - 1);
								groupService.merge(groupObject);
							}
							group.setUp(newUp);
							group = (Group) groupService.merge(group);
						}

					}

				}

				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(PageConstants.MSG, msg);
				request.setAttribute(PageConstants.GROUP, group);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void getGroups(HttpServletRequest request) {
		List<Group> groupList = null;
		int groupNum = 50;
		String groupNumStr = request.getParameter(PageConstants.GROUPNUM);
		if (groupNumStr != null && !Symbols.BLANK.equals(groupNumStr))
			groupNum = Integer.parseInt(groupNumStr);
		GroupService groupService = new GroupService();

		String gid = request.getParameter(PageConstants.ID);
		Group group = null;
		if (gid != null) {
			group = groupService.findById(new Integer(gid));
		}
		if (group.getOpen() == 3)
			request.setAttribute(VIEWER, PageConstants.PAGE_NAME_BOOKMARKSADMIN);
		else
			request.setAttribute(VIEWER, PageConstants.PAGE_NAME_GROUPDETAIL);
		request.setAttribute(PageConstants.GROUP, group);

		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		if (Messages.LANG_EN.equals(lang)) {
			if (group.getOpen() == 1 || group.getOpen() == 2)
				groupList = groupService.findBy3Properties(PageConstants.OPEN,
						group.getOpen(), Messages.LANG_EN, new Integer(1),
						PageConstants.NAV, group.getNav(), 0, groupNum);
			else
				groupList = groupService.findBy2Properties(PageConstants.OPEN,
						group.getOpen(), Messages.LANG_EN, new Integer(1), 0,
						groupNum);
		} else {
			if (group.getOpen() == 1 || group.getOpen() == 2)
				groupList = groupService.findBy3Properties(PageConstants.OPEN,
						group.getOpen(), Messages.LANG_LOCAL, new Integer(1),
						PageConstants.NAV, group.getNav(), 0, groupNum);
			else
				groupList = groupService.findBy2Properties(PageConstants.OPEN,
						group.getOpen(), Messages.LANG_LOCAL, new Integer(1),
						0, groupNum);

		}
		request.setAttribute(PageConstants.GROUPS, groupList);
	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.GROUP_ADMIN);
		return namespaces;
	}

}
